/**
 * 将后端路由数据转换为Vue Router格式
 */
export function transformRoutes(apiRoutes) {
  const rootList = treesToFlatWithPath(apiRoutes) //树形结构扁平化

  //vite动态引入不好用,只能先引入所有组件
  const modules = import.meta.glob('@/views/**/*.vue')
  let pagedata = {}
  Object.keys(modules).forEach((key) => {
    pagedata[key.replace(/^.*?views/, '')] = modules[key]
  }) //去掉views之前的前缀 防止生产环境不好用

  return rootList.map((route) => {
    const pathUrl = route.menuUrl.startsWith('/') ? route.menuUrl.slice(1) : route.menuUrl
    const transformedRoute = {
      path: pathUrl,
      name: route.menuName,
      component: pagedata[`/${pathUrl}/index.vue`] || import('@/views/NotFound.vue'),
      meta: route.meta || {},
    }
    return transformedRoute
  })
}

/**
 * 将树形结构数组转换为扁平结构，包含parentId和路径名称
 * @param {Array} treeArray 树形结构数组
 * @param {number|null} parentId 父节点ID（根节点为null）
 * @param {string} parentPath 父节点路径（根节点为空字符串）
 * @returns {Array} 扁平化后的数组
 */
export function treesToFlatWithPath(treeArray, parentId = null, parentPath = []) {
  let result = []

  treeArray.forEach((tree) => {
    // 当前节点的路径
    // const currentPath = parentPath ? `${parentPath}/${tree.menuName}` : tree.menuName
    const currentPath = [
      ...parentPath,
      {
        menuUrl: tree.menuUrl,
        menuName: tree.menuName,
      },
    ]

    // 创建当前节点的扁平数据
    const flatNode = {
      ...JSON.parse(JSON.stringify(tree)),
      parentId: parentId,
      path: currentPath,
    }
    // delete flatNode.children

    result.push(flatNode)

    // 处理子节点
    if (tree.children && tree.children.length) {
      result = result.concat(treesToFlatWithPath(tree.children, tree.menuId, currentPath))
    }
  })

  return result
}

/**
 * 为树形结构数组添加path属性（不改变原有结构）
 * @param {Array} treeArray 树形结构数组
 * @param {string} parentPath 父节点路径
 * @returns {Array} 添加了path属性的树数组
 */
export function addPathToTrees(treeArray, parentPath = []) {
  if (!Array.isArray(treeArray)) return []

  return treeArray.map((tree) => {
    if (!tree || typeof tree !== 'object') return tree

    // const currentPath = parentPath ? `${parentPath}/${tree.menuName}` : tree.menuName
    const currentPath = [
      ...parentPath,
      {
        menuUrl: tree.menuUrl,
        menuName: tree.menuName,
      },
    ]
    const newTree = {
      ...tree,
      path: currentPath,
    }

    if (tree.children && tree.children.length) {
      newTree.children = addPathToTrees(tree.children, currentPath)
    } else {
      newTree.children = []
    }

    return newTree
  })
}

//找出第一个无子节点菜单
export const findFirstLeafInOrder = (tree) => {
  for (const node of tree) {
    if (!node.children || node.children.length === 0) {
      return node
    }
    if (node.children) {
      const childResult = findFirstLeafInOrder(node.children)
      if (childResult) return childResult
    }
  }
  return null
}
